<!--  -->
<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <el-button class="mtb10" type="primary" @click="getCategoryLever2List">添加分类</el-button>
      <!-- 表格 -->
      <table-tree
        :data="categoryList.result"
        :columns="columns"
        :tree-type="true"
        :selection-type="false"
        :expand-type="false"
        border
        show-index
        index-text="#"
        :show-row-hover="false"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i v-if="scope.row.cat_deleted" class="el-icon-error" style="color:red"></i>
          <i v-else class="el-icon-success" style="color:lightgreen"></i>
        </template>
        <!-- 排序 -->
        <template slot="lever" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag size="mini" v-else-if="scope.row.cat_level===1" type="success">二级</el-tag>
          <el-tag size="mini" v-else type="warning">三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="operation" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="editRowCategory(scope.row)"
          >编辑</el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="deleteCategory(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </table-tree>
      <!-- 分页栏 -->
      <el-pagination
        class="mtb10"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[3, 5, 10, 15]"
        :current-page.sync="params.pagenum"
        :page-size="params.pagesize"
        :total="categoryList.total"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </el-card>
    <!-- dirlog -->
    <!-- 添加分类dirlog -->
    <el-dialog
      title="添加分类"
      @close="addCategoryDialogClose"
      :visible.sync="addCategoryDialogVisible"
      width="50%"
    >
      <el-form :model="addCategoryForm" :rules="rules" ref="addCategoryForm" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCategoryForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- 级联选择器 -->
          <!-- :options指定数据源,:props配置选项 -->
          <!-- v-model绑定的数据就是选中的数据值 -->
          <!-- change-on-select可以选中所有菜单项 -->
          <el-cascader
            clearable
            v-model="cascaderIds"
            :options="categoryLever2List"
            :props="cascaderProps"
            @change="handleCascaderChange"
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddCategory">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类dirlog -->
    <el-dialog title="修改分类" :visible.sync="editCategoryDialogVisible" width="50%">
      <el-form :model="editCategoryForm" :rules="rules" ref="editCategoryForm" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCategoryForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCategoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCategory">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  name: 'GoodsCategory',
  components: {},
  data() {
    return {
      params: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      categoryList: {},
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
          width: ''
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'lever'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operation'
        }
      ],
      addCategoryDialogVisible: false,
      addCategoryForm: {
        cat_name: '',
        cat_pid: '',
        cat_level: ''
      },
      rules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      //前两级列表数据
      categoryLever2List: [],
      //被选项的数据
      cascaderIds: [],
      //指定级联选择器的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      editCategoryDialogVisible: false,
      editCategoryForm: {}
    }
  },
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getCategoryList()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  methods: {
    async getCategoryList() {
      let { data: res } = await this.$http.get('categories', {
        params: this.params
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.categoryList = res.data
    },
    handleSizeChange(e) {
      this.params.pagesize = e
      this.getCategoryList()
    },
    handleCurrentChange(e) {
      this.params.pagenum = e
      this.getCategoryList()
    },
    async getCategoryLever2List() {
      this.params.type = 2
      this.addCategoryDialogVisible = true
      let { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.categoryLever2List = res.data
    },
    addCategoryDialogClose() {
      this.addCategoryForm = {
        cat_name: '',
        cat_pid: '',
        cat_level: ''
      }
      this.cascaderIds = []
    },
    handleCascaderChange() {
      this.addCategoryForm.cat_level = this.cascaderIds.length
      this.addCategoryForm.cat_pid = this.cascaderIds.length
        ? this.cascaderIds[this.cascaderIds.length - 1]
        : 0
    },
    saveAddCategory() {
      this.$refs.addCategoryForm.validate(async valid => {
        if (!valid) return
        console.log(this.addCategoryForm)
        let { data: res } = await this.$http.post(
          'categories',
          this.addCategoryForm
        )
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('分类数据添加成功')
        this.getCategoryList()
        this.addCategoryDialogVisible = false
      })
    },
    editRowCategory(info) {
      this.editCategoryDialogVisible = true
      this.editCategoryForm = info
    },
    async saveCategory() {
      let { data: res } = await this.$http.put(
        'categories/' + this.editCategoryForm.cat_id,
        {
          cat_name: this.editCategoryForm.cat_name
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getCategoryList()
      this.$message.success(res.meta.msg)
      this.editCategoryDialogVisible = false
    },
    deleteCategory(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let { data: res } = await this.$http.delete('categories/' + id)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.getCategoryList()
          this.$message.success(res.meta.msg)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>
<style scoped>
</style>